from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from article.models import Channel, Article, Comment
from article.search_indexes import ArticleIndex
from personal.models import User


class ChannelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Channel
        fields = '__all__'


# =============== 文章详情 =========================
class UserArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields = ('id', 'title')


class UserSerializer(serializers.ModelSerializer):

    articles = UserArticleSerializer()
    fans = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'avatar', 'articles', 'fans')


class CommentsSubsSerializer(serializers.ModelSerializer):

    user = UserSerializer()
    subs = serializers.StringRelatedField(read_only=True, many=True)

    class Meta:
        model = Comment
        fields = ('id', 'content', 'article', 'user', 'parent', 'subs', 'createtime')


class CommentsArticleSerializer(serializers.ModelSerializer):

    user = UserSerializer()
    subs = CommentsSubsSerializer(many=True)

    class Meta:
        model = Comment
        fields = '__all__'


class DetailArticleSerializer(serializers.ModelSerializer):

    user = UserSerializer()
    comments = CommentsArticleSerializer(many=True)
    collected_users = serializers.StringRelatedField(read_only=True, many=True)

    class Meta:
        model = Article
        fields = '__all__'

# ===================   文章详情  ==========================


# 文章列表，发布文章
class ArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields = '__all__'


# 评论文章
class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Comment
        fields = '__all__'

    def create(self, validated_data):

        super().create(validated_data)

        article_id = validated_data['article']
        article = Article.objects.get(id=article_id)
        article.comment_count += 1
        article.save()


# 搜索文章
class ArticleIndexSerializer(HaystackSerializer):

    class Meta:
        index_classes = ArticleIndex
        fields = ('id', 'text', 'createtime', 'content', 'title')



